package com.cl.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cl.request.*;
import com.cl.util.CommonUtil;
import com.cl.util.EntityNameReplaceUtil;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cl.dao.CommonDao;
import com.cl.dao.SearchDao;
import com.cl.dto.ComboTreeDTO;
import com.cl.dto.PayDTO;
import com.cl.dto.ResultDTO;
import com.cl.dto.WordDTO;
import com.cl.entity.*;
import com.cl.service.CommonService;
import com.cl.service.MSOfficeService;
//import com.cl.service.payGrant.PayGrantExcelService;
import com.cl.service.payGrant.PayGrantExcelService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class ApiController {
	@Autowired
	private CommonDao commonDao;

	@Autowired
	private CommonService commonService;

	@Autowired
	private MSOfficeService msOfficeService;

	@Autowired
	private PayGrantExcelService pges;

	@Autowired
	private CommonUtil commonUtil;

	@SuppressWarnings("rawtypes")
	@Autowired
	private SearchDao searchDao;

	/**
	 * 获得指定word文件的纯文本及其字数
	 * 
	 * @param fp
	 * @return
	 */
	@RequiresPermissions("*:view")
	@RequestMapping(value = "/api/wordtxt", method = RequestMethod.GET)
	@ResponseBody
	public WordDTO getWordTxt(@RequestParam(value = "fp", required = true) String fp) throws Exception {
		if (fp.endsWith("docx"))
			return msOfficeService.getXWordTxt(fp);
		else
			return msOfficeService.getWordTxt(fp);
	}

	@SuppressWarnings("rawtypes")
	@RequiresPermissions("*:view")
	@RequestMapping(value = "/ls/{entity}/{property}", method = RequestMethod.GET)
	@ResponseBody
	public ResultDTO listEntities(@PathVariable String entity, @PathVariable String property,
			@RequestParam(value = "limit", required = false) int limit,
			@RequestParam(value = "kw", required = false) String kw,
			@RequestParam(value = "filter", required = false) String filter,
			@RequestParam(value = "sort", required = false) String sort) throws ClassNotFoundException {
		return commonService.listEntities(entity, property, kw, limit,filter,sort);
	}

	@SuppressWarnings({ "unchecked" })
	@RequiresPermissions("*:view")
	@RequestMapping(value = "/distinct/{entity}/{property}", method = RequestMethod.GET)
	@ResponseBody
	public ResultDTO<Object> distinct(@PathVariable String entity, @PathVariable String property,
			@RequestParam(value = "limit", required = false) int limit,
			@RequestParam(value = "kw", required = false) String kw,
			@RequestParam(value = "filter", required = false) String filter) throws ClassNotFoundException {
		return commonService.disticnt(entity, property, kw, limit,filter);
	}

	/**
	 * 过滤、排序、分页查询实体信息
	 * 
	 * @param page
	 *            页码
	 * @param start
	 *            开始记录数
	 * @param limit
	 *            页记录数
	 * @param filter
	 *            过滤条件
	 * @param sort
	 *            排序条件
	 * @return 实体信息
	 * @throws ClassNotFoundException
	 */
	@SuppressWarnings("rawtypes")
	@RequiresPermissions("*:view")
	@RequestMapping(value = "/list/{entity}", method = RequestMethod.GET)
	@ResponseBody
	public ResultDTO getEntities(@PathVariable String entity, @RequestParam(value = "page", required = true) int page,
			@RequestParam(value = "start", required = true) int start,
			@RequestParam(value = "limit", required = true) int limit,
			@RequestParam(value = "filter", required = false) String filter,
			@RequestParam(value = "sort", required = false) String sort) throws ClassNotFoundException {
		return commonService.getEntities(page, start, limit, filter, sort, entity);
	}

	/**
	 * list中编辑页面，仅限于Ext.data.Store
	 * 
	 * @param id
	 * @param request
	 * @param httpRequest
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequiresPermissions("*:update")
	@RequestMapping(value = "/list/{entity}/{id}", method = RequestMethod.PUT)
	@ResponseBody
	public <T> T getEntities(@PathVariable String entity, @PathVariable Long id,
			@RequestBody Map<String, Object> request, HttpServletRequest httpRequest)
					throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		String ip = commonUtil.getIpAddress(httpRequest);
		return (T) commonService.updateEntity(entity, request, ip);
	}

	/**
	 * 获取关联的实体信息
	 * 
	 * @param filter
	 *            关联条件
	 * @return 关联的实体信息
	 * @throws ClassNotFoundException
	 */
	@SuppressWarnings("rawtypes")
	@RequiresPermissions("*:view")
	@RequestMapping(value = "/rest/{entity}", method = RequestMethod.GET)
	@ResponseBody
	public List relEntities(@PathVariable String entity,
			@RequestParam(value = "filter", required = false) String filter) throws ClassNotFoundException {
		if(!StringUtils.isEmpty(filter)){
			filter = filter.replaceAll("thesiId", "thesisId");
		}
		return commonService.getRelEntities(entity, filter);
	}

	/**
	 * 创建一个空的实体
	 * 
	 * @return
	 * @throws ClassNotFoundException
	 */
	@SuppressWarnings("unchecked")
	@RequiresPermissions("*:create")
	@RequestMapping(value = "/rest/{entity}", method = RequestMethod.POST)
	@ResponseBody
	public <T> T createEntity(@PathVariable String entity, @RequestBody Map<String, Object> request,
			HttpServletRequest httpRequest) throws ClassNotFoundException {
		String ip = commonUtil.getIpAddress(httpRequest);
		T po= commonService.getEntity(entity, null, ip);	
		commonService.setEntityProp(po,request,ip);
		return po;
	}

	/**
	 * 获取一个实体信息
	 * 
	 * @param id
	 *            实体的主键ID
	 * @return 实体信息
	 * @throws ClassNotFoundException
	 */
	@SuppressWarnings("unchecked")
	@RequiresPermissions("*:view")
	@RequestMapping(value = "/rest/{entity}/{id}", method = RequestMethod.GET)
	@ResponseBody
	public <T> T getEntity(@PathVariable String entity, @PathVariable long id, HttpServletRequest httpRequest)
			throws ClassNotFoundException {
		String ip = commonUtil.getIpAddress(httpRequest);
		return (T) commonService.getEntity(entity, id, ip);
	}

	/**
	 * 更新实体信息
	 * 
	 * @param id
	 *            实体的主健ID
	 * @param request
	 *            修改的实体信息
	 * @return 更新后的实体信息
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 */
	@SuppressWarnings("unchecked")
	@RequiresPermissions("*:update")
	@RequestMapping(value = "/rest/{entity}/{id}", method = RequestMethod.PUT)
	@ResponseBody
	public <T> T updateEntity(@PathVariable String entity, @PathVariable Object id,
			@RequestBody Map<String, Object> request, HttpServletRequest httpRequest)
					throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		String ip = commonUtil.getIpAddress(httpRequest);
		return (T) commonService.updateEntity(entity, request, ip);
	}

	/**
	 * 增加关联
	 * 
	 * @param request
	 * @return
	 */
	@RequiresPermissions("*:create")
	@RequestMapping(value = "/rel/add", method = RequestMethod.POST)
	@ResponseBody
	public List<Rel> addRel(@RequestBody RelRequest request, HttpServletRequest httpRequest) {
		String ip = commonUtil.getIpAddress(httpRequest);
		//兼容历史数据对REL表中THESIS_CATALOG的特殊处理
		/*
		if(request.entity1.contains("THESISCATALOG"))
			request.entity1 = request.entity1.replace("THESISCATALOG", "THESIS_CATALOG");
		if(request.entity2.contains("THESISCATALOG"))
			request.entity2 = request.entity2.replace("THESISCATALOG", "THESIS_CATALOG");
		*/
		request.entity1 = EntityNameReplaceUtil.replaceName(request.entity1);
		request.entity2 = EntityNameReplaceUtil.replaceName(request.entity2);
		return commonService.addRel(request, ip);
	}

	/**
	 * 删除关联
	 * 
	 * @param request
	 * @return
	 */
	@RequiresPermissions("*:delete")
	@RequestMapping(value = "/rel/delete", method = RequestMethod.POST)
	@ResponseBody
	public void deleteRel(@RequestBody RelRequest request, HttpServletRequest httpRequest) {
		String ip = commonUtil.getIpAddress(httpRequest);
		
		//兼容历史数据对REL表中THESIS_CATALOG的特殊处理
		/*
		if(request.entity1.contains("THESISCATALOG"))
			request.entity1 = request.entity1.replace("THESISCATALOG", "THESIS_CATALOG");
		if(request.entity2.contains("THESISCATALOG"))
			request.entity2 = request.entity2.replace("THESISCATALOG", "THESIS_CATALOG");
		*/
		request.entity1 = EntityNameReplaceUtil.replaceName(request.entity1);
		request.entity2 = EntityNameReplaceUtil.replaceName(request.entity2);
		commonService.deleteRel(request, ip);
	}

	/**
	 * 删除
	 * 
	 * @param request
	 * @return
	 */
	@RequiresPermissions("*:delete")
	@RequestMapping(value = "/api/remove", method = RequestMethod.POST)
	@ResponseBody
	public void removeEntities(@RequestBody RemoveRequest request, HttpServletRequest httpRequest) {
		String ip = commonUtil.getIpAddress(httpRequest);
		commonService.deleteEntities(request, ip);
	}
	/*-----------------------------以上为公用rest服务----------------------------*/

	/**
	 * 创建用户
	 * 
	 * @return
	 * @throws ClassNotFoundException
	 */
	@SuppressWarnings("unchecked")
	@RequiresPermissions("UUser:create")
	@RequestMapping(value = "/api/UUser", method = RequestMethod.POST)
	@ResponseBody
	public UUser createUuser(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest)
			throws ClassNotFoundException {
		String ip = commonUtil.getIpAddress(httpRequest);
		return commonService.createUser(request, ip);
	}

	/**
	 * 更新用户
	 * 
	 * @param id
	 *            实体的主健ID
	 * @param request
	 *            修改的实体信息
	 * @return 更新后的实体信息
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 */
	@SuppressWarnings("unchecked")
	@RequiresPermissions("UUser:update")
	@RequestMapping(value = "/api/UUser/{id}", method = RequestMethod.PUT)
	@ResponseBody
	public UUser updateUser(@PathVariable Object id, @RequestBody Map<String, Object> request,
			HttpServletRequest httpRequest)
					throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		String ip = commonUtil.getIpAddress(httpRequest);
		// 密码要特别处理
		return commonService.updateUser(id, request, ip);
	}

	@RequiresPermissions("*:view")
	@RequestMapping(value = "/api/WorkLoad", method = RequestMethod.GET)
	@ResponseBody
	public ResultDTO getWorkLoad(@RequestParam(value = "filter", required = false) String filter) {
		return commonService.getWorkLoadEntities(filter);
	}

	/**
	 * 稿酬批量确认
	 * 
	 * @param request
	 * @param httpRequest
	 * @return
	 */
	@RequiresPermissions("*:update")
	@RequestMapping(value = "/api/ConfirmPay", method = RequestMethod.POST)
	@ResponseBody
	public List<CcPay> confirmPay(@RequestBody PayRequest request, HttpServletRequest httpRequest) {
		String ip = commonUtil.getIpAddress(httpRequest);
		return commonService.confirmPays(request, ip);
	}
	
	@RequiresPermissions("*:update")
	@RequestMapping(value = "/api/batchConfirmPay", method = RequestMethod.POST)
	@ResponseBody
	public void batchConfirmPay(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
		String ip = commonUtil.getIpAddress(httpRequest);
		commonService.batchConfirmPays(request, ip);
	}
	
	@RequiresPermissions("*:update")
	@RequestMapping(value = "/api/batchEditorConfirmPay", method = RequestMethod.POST)
	@ResponseBody
	public void batchEditorConfirmPay(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) throws ClassNotFoundException {
		String ip = commonUtil.getIpAddress(httpRequest);
		commonService.batchEditorConfirmPays(request, ip);
	}

	/**
	 * 稿酬发放
	 *
	 * @param fp
	 * @return
	 */
	@SuppressWarnings("deprecation")
	@RequiresPermissions("*:view")
	@RequestMapping(value = "/api/payGrant", method = RequestMethod.GET)
	@ResponseBody
	public PayDTO generateExcel(HttpServletRequest request,
			@RequestParam(value = "zfpd_id", required = true) String zfpd_id,
			@RequestParam(value = "bgTM", required = true) String bgTM,
			@RequestParam(value = "endTM", required = true) String endTM,
			@RequestParam(value = "bPreview", required = true) boolean bPreview) throws Exception {
		return  pges.generateExcel(request,zfpd_id,bgTM,endTM,bPreview);
	}

	@RequiresPermissions("*:update")
	@RequestMapping(value = "/api/CaculatePay", method = RequestMethod.POST)
	@ResponseBody
	public List<CcPay> caculatePay(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest)
			throws Exception {
		String ip = commonUtil.getIpAddress(httpRequest);
		String entity = (String) request.get("entity");
		Map<String, Object> modified = (Map<String, Object>) request.get("modified");
		Long id = Long.valueOf((Integer) modified.get("id"));

		String keyField = commonService.getKeyField(entity);
		// Map<String, Object> changed =
		modified.remove("id");
		modified.put(keyField, id);

		if (modified != null) {
			commonService.updateEntity(entity, modified, ip);
		}
		return commonService.caculatePay(entity, id, ip);

	}

	@RequiresPermissions("*:update")
	@RequestMapping(value = "/api/dragDropSort", method = RequestMethod.POST)
	@ResponseBody
	public void dragDropSort(@RequestBody OrderRequest sort) {
		commonService.dragDropSort(sort);
	}

	@SuppressWarnings({ "unchecked" })
	@RequestMapping(value = "/getTreeData/{entity}/{property}", method = RequestMethod.GET)
	@ResponseBody
	public List<ComboTreeDTO> getTreeData(@PathVariable String entity, @PathVariable String property,
			@RequestParam(value = "filter", required = false) String filter) 
			throws ClassNotFoundException
	{
		return commonService.getTreeData(entity, property, filter);
	}
	

	
	
}
